// eslint-disable-next-line no-unused-vars
export function debounce(fn: () => void, timeout = 500, triggleNow = false) {
  let timeId: NodeJS.Timeout | null = null;
  const debounced = () => {
    if (timeId) {
      clearTimeout(timeId);
    }
    if (triggleNow) {
      const exec = !timeId;
      timeId = setTimeout(() => {
        timeId = null;
      }, timeout);
      if (exec) {
        fn();
      }
    } else {
      timeId = setTimeout(() => {
        fn();
      }, timeout);
    }
  };
  debounced.remove = function () {
    clearTimeout(timeId as NodeJS.Timeout);
    timeId = null;
  };
  return debounced;
}

export function throttle(fn: () => void, timeout = 1000) {
  let timeId: NodeJS.Timeout | null = null,
    begin = Date.now();
  return () => {
    const cur = Date.now();
    clearTimeout(timeId as NodeJS.Timeout);
    if (cur - begin >= timeout) {
      fn();
      begin = cur;
    } else {
      timeId = setTimeout(() => {
        fn();
      }, timeout);
    }
  };
}
